//网络请求
import axios from 'axios';
import AppConfig from '@/constants/AppConfig.js';

const $axios = axios;

export default function() {
	var $app_config = AppConfig();
	var $base_url = $app_config.Base_Url;
	var $post_config = $app_config.POST_Cfg;
	//登录
	var $url_getToken = $base_url + "/admin/qiniu/v1/getToken";
	var $this = {
		getQiniuToken: function() {
			return new Promise(function(resolve, reject) {
				$axios.post($url_getToken, {
					}, $post_config)
					.then(function(response) {
						console.log(response);
						resolve(response);
					})
					.catch(function(err) {
						reject(err);
					});
			});
		},
		uploadBase642QiniuServer: function(data, loadStart, progress) {
			return new Promise(function(resolve, reject) {
				$this.getQiniuToken().then(function(response) {
					var res = response.data;
					if(res.rescode == 100) {
						var token = res.data;
						var pic = data.replace(/^.*?,/, '');
						var url = "http://upload-z1.qiniu.com/putb64/-1"; //非华东空间需要根据注意事项 1 修改上传域名
						var xhr = new XMLHttpRequest();
						xhr.onload = function() {
							resolve({
								state: 1,
								data: xhr.responseText
							});
						}; //请求完成
			            xhr.onerror =  function() {
			            		resolve({
								state: -1
							});
			            }; //请求失败
			            xhr.upload.onloadstart = loadStart;
//						xhr.onreadystatechange = function() {
//							if (xhr.readyState == 4) {
//								resolve(xhr.responseText);
//							}
//						}
						xhr.onprogress = progress;
						xhr.open("POST", url, true);
						xhr.setRequestHeader("Content-Type", "application/octet-stream");
						xhr.setRequestHeader("Authorization", "UpToken " + token);
						xhr.send(pic);
					} else {
						reject("七牛token错误");
					}
				}, function(error) {
					reject("七牛token错误");
				});
			});
		}
	}
	return $this;
}